package com.example.photographWatermark_example

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PixelFormat
import android.hardware.Camera
import android.hardware.Camera.PictureCallback
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.SurfaceHolder
import androidx.core.content.FileProvider
import com.example.photographWatermark_example.camera2.CameraActivity
import kotlinx.android.synthetic.main.activity_photo.*
import kotlinx.android.synthetic.main.activity_photo1.*
import java.io.File


class PhotoActivity : Activity(),SurfaceHolder.Callback2{

    private lateinit var mSurfaceHolder:SurfaceHolder
    private lateinit var mCamera: Camera
    private var mCameraInfo:Camera.CameraInfo = Camera.CameraInfo()
    private var mCameraId:Int = 0



    private val filePath =  Environment.getExternalStorageDirectory().path
    private val REQUEST_CODE_TAKE_PICTURE = 1000
    private  val AUTHORITY = "com.cs.camerademo.fileProvider"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_photo1)
        setContentView(R.layout.activity_photo)
//        val imgPath = intent.getStringExtra("camera")
//        val bm = BitmapFactory.decodeFile(imgPath)
//        image_idcard.setImageBitmap(bm)
//        restart_btn.setOnClickListener {
//            val intent = Intent(this, CameraActivity::class.java)
//            startActivity(intent)
//        }

        mSurfaceHolder = sfv_camera.holder
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
        mSurfaceHolder.setKeepScreenOn(true)
        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT)
        mSurfaceHolder.addCallback(this)
        mCameraId =  Camera.CameraInfo.CAMERA_FACING_BACK
        sfv_camera.setOnTouchListener { v, event ->
            mCamera.autoFocus(autoFocusCallback)
            return@setOnTouchListener false
        }


        btn_takePic.setOnClickListener {
            mCamera.takePicture(null, null, PictureCallback { data, camera ->
                val bitmap = BitmapFactory.decodeByteArray(data,0,data.size)
//                bitmap = Image
            })
        }

    }

    private val autoFocusCallback = Camera.AutoFocusCallback { success, camera
        ->  }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.d("-----","-====")
        if(resultCode== RESULT_OK){
            when(requestCode){
                REQUEST_CODE_TAKE_PICTURE-> print("-----")
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun surfaceRedrawNeeded(holder: SurfaceHolder?) {
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
        startPreview(mCamera,mSurfaceHolder)
//        mCamera.startPreview()
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        mCamera.stopPreview()
        mCamera.release()
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
       try {
           mCamera = Camera.open(mCameraId)
           Camera.getCameraInfo(mCameraId,mCameraInfo)
       }catch (e:java.lang.Exception){

       }
    }

    override fun onStart() {
        openCamera()
        super.onStart()
    }
    private fun openCamera(){
        val cameraInfo = Camera.CameraInfo()
        Camera.getCameraInfo(mCameraId,cameraInfo)
        mCameraInfo = cameraInfo
        if(mCameraId==Camera.CameraInfo.CAMERA_FACING_BACK){
            mCamera = Camera.open()
            mCamera.startPreview()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        mCamera.stopPreview()
        mCamera.release()
    }
    private fun startPreview(camera: Camera,surfaceHolder: SurfaceHolder){
//        camera.setDisplayOrientation()
        camera.startPreview()
    }

//    class PicCallBackImpl :android.hardware.Camera.PictureCallback{
//        override fun onPictureTaken(data: ByteArray?, camera: android.hardware.Camera?) {
//            TODO("Not yet implemented")
//        }
//
//    }



    private fun startCamera(){
        val imageFile = createImageFile()
        imageFile?.let {
            val intent = Intent()
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //如果是7.0以上，使用FileProvider，否则会报错
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                val imgUri = FileProvider.getUriForFile(this, AUTHORITY, it)
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri) //设置拍照后图片保存的位置
            } else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(it)) //设置拍照后图片保存的位置
            }
            intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString())
            intent.resolveActivity(packageManager)?.let {
                startActivityForResult(intent,REQUEST_CODE_TAKE_PICTURE)
            }
        }

    }
    //生成一个文件
    fun createImageFile(): File? {
        return try {
            val rootFile = File(filePath + File.separator + "capture")
            if (!rootFile.exists())
                rootFile.mkdirs()
            val fileName =   "${System.currentTimeMillis()}.jpg";
            File(rootFile.absolutePath + File.separator + fileName)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

}